import { memo, useState, useEffect, useCallback } from 'react';
import { Avatar, Tabs, Card, Statistic, Button, Upload, Input, Modal, Form, Empty } from 'antd';
import {
  UserOutlined,
  EditOutlined,
  BookOutlined,
  SettingOutlined,
  TeamOutlined,
  UploadOutlined,
  CheckOutlined,
} from '@ant-design/icons';
import type { StatisticProps, TabsProps } from 'antd';
import CountUp from 'react-countup';
import useUserInfoStore from '@/store/useUserInfo';
import { useShallow } from 'zustand/shallow';
import {
  CourseList,
  getMyCommentCountApi,
  getMyCourseListApi,
  getUserInfoApi,
  updatePasswordApi,
  updatePhoneApi,
  updateUserInfoApi,
  uploadFileApi,
} from '@/api/api';
import useApp from 'antd/es/app/useApp';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';

// 格式化数字
const formatter: StatisticProps['formatter'] = (value: any) => (
  <CountUp
    end={value}
    separator=","
  />
);

// 个人中心页面组件
const IndividualCenter = () => {
  const navigate = useNavigate();
  const app = useApp();
  // 修改密码 form
  const [passwordForm] = Form.useForm();
  // 换绑手机号 form
  const [phoneForm] = Form.useForm();
  //修改密码还是换绑手机号
  const [type, setType] = useState<'password' | 'phone'>('password');
  // 是否显示modal
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 用户信息状态
  const { userInfo, setUserInfo, setToken } = useUserInfoStore(
    useShallow((state) => {
      return {
        userInfo: state.userInfo,
        setUserInfo: state.setUserInfo,
        setToken: state.setToken,
      };
    })
  );

  // 编辑模式状态
  const [isEditing, setIsEditing] = useState(false);
  // 编辑昵称
  const [editNickname, setEditNickname] = useState('');
  // 编辑简介
  const [editBio, setEditBio] = useState('');
  // 头像
  const [avatar, setAvatar] = useState('');
  // 头像上传状态
  const [avatarLoading, setAvatarLoading] = useState(false);

  // 课程数据状态
  const [courses, setCourses] = useState<CourseList[]>([]);

  // 评论数
  const [commentCount, setCommentCount] = useState(0);

  const getMyCourseList = useCallback(async () => {
    const res = await getMyCourseListApi();
    if (res.code === 200) {
      setCourses(res.data);
    }
  }, []);

  // 获取我的评论数
  const getMyCommentCount = useCallback(async () => {
    const res = await getMyCommentCountApi();
    if (res.code === 200) {
      setCommentCount(res.data);
    }
  }, []);
  // 保存编辑信息
  const handleSaveProfile = async () => {
    const res = await updateUserInfoApi({
      username: editNickname,
      avatar: avatar,
      phone: userInfo.phone,
      bio: editBio,
    } as any);
    if (res.code === 200) {
      setUserInfo({
        ...userInfo,
        username: editNickname,
        bio: editBio,
        avatar: avatar,
      });
      setIsEditing(false);
      // 获取修改后的用户信息
      getUserInfo();
      app.message.success('个人信息已更新');
    }
  };

  // 取消编辑
  const handleCancelEdit = () => {
    setEditNickname(userInfo.username);
    setEditBio(userInfo.bio);
    setAvatar(userInfo.avatar);
    setIsEditing(false);
  };

  // 处理头像上传
  const handleAvatarChange = (info: any) => {
    if (info.file.status === 'uploading') {
      setAvatarLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // 模拟上传成功，实际应用中应使用服务器返回的URL
      app.message.success('头像上传成功');
      setAvatarLoading(false);
    }
  };

  // 自定义上传
  const customRequest = async (options: any) => {
    const formData = new FormData();
    formData.append('img', options.file);
    const res = await uploadFileApi(formData);
    if (res.code === 200) {
      setAvatar(res.data);
      options.onSuccess();
    }
  };

  // 标签页内容定义
  const tabItems: TabsProps['items'] = [
    {
      key: '1',
      label: (
        <span>
          <BookOutlined /> 我的课程
        </span>
      ),
      children: (
        <div className="grid grid-[repeat(auto-fill,minmax(200px,1fr))] gap-4">
          {courses.length > 0 ? (
            courses.map((course, index) => (
              <div
                key={course.id}
                className="card-animate"
                style={{ animationDelay: `${0.1 * index}s` }}
              >
                <Card
                  hoverable
                  className="mb-4 transition-all hover:shadow-md"
                >
                  <div className="flex justify-between items-center mb-2">
                    <h3 className="text-lg font-medium">{course.name}</h3>
                    <Button
                      type="primary"
                      size="small"
                      onClick={() => navigate(`/classroom/${course.id}`)}
                    >
                      继续学习
                    </Button>
                  </div>
                  <div>
                    <div className="flex justify-between text-sm text-gray-500 mb-1">
                      <span>上次学习: {dayjs(course.updated_at).format('YYYY-MM-DD')}</span>
                    </div>
                  </div>
                </Card>
              </div>
            ))
          ) : (
            <Empty
              description="暂无我的课程信息"
              className="w-full h-full"
            />
          )}
        </div>
      ),
    },
    {
      key: '4',
      label: (
        <span>
          <SettingOutlined /> 账户设置
        </span>
      ),
      children: (
        <div className="space-y-6">
          <div
            className="card-animate"
            style={{ animationDelay: '0.2s' }}
          >
            <Card
              title="账号安全"
              className="mb-4 transition-all hover:shadow-md"
            >
              <div className="space-y-4">
                <div className="flex justify-between items-center">
                  <span>修改密码</span>
                  <Button
                    onClick={() => {
                      setType('password');
                      setIsModalOpen(true);
                    }}
                    icon={<SettingOutlined />}
                    className="hover:scale-105 transition-transform"
                  >
                    修改
                  </Button>
                </div>
                <div className="flex justify-between items-center">
                  <span>当前绑定的手机号：{userInfo.phone}</span>
                  <Button
                    onClick={() => {
                      setType('phone');
                      setIsModalOpen(true);
                    }}
                    icon={<SettingOutlined />}
                    className="hover:scale-105 transition-transform"
                  >
                    修改
                  </Button>
                </div>
              </div>
            </Card>
          </div>
        </div>
      ),
    },
  ];

  // 获取用户信息
  const getUserInfo = useCallback(async () => {
    const res = await getUserInfoApi();
    if (res.code === 200) {
      setUserInfo(res.data);
      setAvatar(res.data.avatar);
      setEditNickname(res.data.username);
      setEditBio(res.data.bio);
    }
  }, [setUserInfo]);

  // 更新编辑状态的表单值
  useEffect(() => {
    // 获取用户昵称
    setEditNickname(userInfo.username);
    // 获取用户简介
    setEditBio(userInfo.bio);
  }, [getUserInfo, userInfo]);

  useEffect(() => {
    getUserInfo();
    getMyCourseList();
    getMyCommentCount();
  }, [getUserInfo, getMyCourseList, getMyCommentCount]);

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* 个人信息卡片 */}
        <div className="bg-white rounded-lg shadow-md overflow-hidden mb-8 transition-all hover:shadow-lg fade-in">
          <div className="relative h-32 bg-gradient-to-r from-blue-500 to-purple-600">
            {/* 编辑按钮 */}
            <div className="absolute top-4 right-4">
              {isEditing ? (
                <div className="space-x-2">
                  <Button
                    icon={<CheckOutlined />}
                    type="primary"
                    onClick={handleSaveProfile}
                    className="hover:scale-105 transition-transform"
                  >
                    保存
                  </Button>
                  <Button
                    onClick={handleCancelEdit}
                    className="hover:scale-105 transition-transform"
                  >
                    取消
                  </Button>
                </div>
              ) : (
                <Button
                  icon={<EditOutlined />}
                  type="primary"
                  ghost
                  onClick={() => setIsEditing(true)}
                  className="hover:scale-105 transition-transform !text-white border !border-white"
                >
                  编辑资料
                </Button>
              )}
            </div>
          </div>

          <div className="flex flex-col md:flex-row md:items-start p-6 pt-0">
            {/* 头像区域 */}
            <div className="relative -mt-16 z-10 mx-auto md:mx-0 mb-4 md:mb-0 md:mr-6">
              <Avatar
                size={96}
                src={avatar}
                icon={<UserOutlined />}
                className="border-4 border-white shadow-lg transition-all hover:shadow-xl avatar-animate"
              />

              {isEditing && (
                <div className="absolute bottom-0 right-0 fade-in">
                  <Upload
                    name="avatar"
                    showUploadList={false}
                    customRequest={customRequest}
                    onChange={handleAvatarChange}
                  >
                    <Button
                      icon={<UploadOutlined />}
                      size="small"
                      shape="circle"
                      loading={avatarLoading}
                      className="hover:scale-110 transition-transform"
                    />
                  </Upload>
                </div>
              )}
            </div>

            {/* 用户信息区域 */}
            <div className="flex-1 fade-in-up">
              {/* 昵称 */}
              <div className="mb-2">
                {isEditing ? (
                  <Input
                    value={editNickname}
                    onChange={(e) => setEditNickname(e.target.value)}
                    placeholder="输入昵称"
                    maxLength={20}
                    className="text-xl font-bold w-full sm:w-64"
                  />
                ) : (
                  <h2 className="text-xl font-bold">{userInfo.username}</h2>
                )}
              </div>

              {/* 个人简介 */}
              <div className="mb-4">
                {isEditing ? (
                  <Input.TextArea
                    value={editBio}
                    onChange={(e) => setEditBio(e.target.value)}
                    placeholder="介绍一下自己吧..."
                    autoSize={{ minRows: 2, maxRows: 4 }}
                    maxLength={100}
                    className="text-sm text-gray-600 w-full sm:w-96"
                  />
                ) : (
                  <p className="text-sm text-gray-600">{userInfo.bio}</p>
                )}
              </div>

              {/* 数据统计 */}
              <div className="flex flex-wrap gap-6">
                <Statistic
                  title="课程数"
                  value={courses.length}
                  formatter={formatter}
                  prefix={<BookOutlined className="text-blue-500" />}
                />
                <Statistic
                  title="评论数"
                  value={commentCount}
                  formatter={formatter}
                  prefix={<TeamOutlined className="text-green-500" />}
                />
              </div>
            </div>
          </div>
        </div>

        {/* 标签页内容 */}
        <div
          className="fade-in"
          style={{ animationDelay: '0.3s' }}
        >
          <Tabs
            defaultActiveKey="1"
            items={tabItems}
            animated={{ inkBar: true, tabPane: true }}
          />
        </div>
        <Modal
          open={isModalOpen}
          title={type === 'password' ? '修改密码' : '换绑手机号'}
          onOk={async () => {
            if (type === 'password') {
              passwordForm.validateFields();
              const res = await updatePasswordApi({
                oldPassword: passwordForm.getFieldValue('oldPassword'),
                newPassword: passwordForm.getFieldValue('newPassword'),
              });
              if (res.code === 200) {
                app.message.success('密码修改成功,即将返回登录页面');
                setIsModalOpen(false);
                setTimeout(() => {
                  setUserInfo({});
                  setToken('');
                  navigate('/login');
                }, 1000);
              } else {
                app.message.error(res.message);
              }
            } else {
              phoneForm.validateFields();
              const res = await updatePhoneApi({
                phone: phoneForm.getFieldValue('phone'),
              });
              if (res.code === 200) {
                app.message.success('手机号换绑成功');
                getUserInfo();
                setIsModalOpen(false);
              } else {
                app.message.error(res.message);
              }
            }
          }}
          onCancel={() => {
            setIsModalOpen(false);
          }}
        >
          {
            // 修改密码还是换绑手机号
            type === 'password' ? (
              <div>
                <Form form={passwordForm}>
                  <Form.Item
                    name="oldPassword"
                    label="旧密码"
                    rules={[
                      { required: true, message: '请输入旧密码' },
                      { min: 6, message: '密码长度在6-16位之间' },
                    ]}
                  >
                    <Input.Password placeholder="请输入旧密码" />
                  </Form.Item>
                  <Form.Item
                    name="newPassword"
                    label="新密码"
                    rules={[
                      { required: true, message: '请输入新密码' },
                      ({ getFieldValue }) => ({
                        validator(_, value) {
                          if (getFieldValue('oldPassword') === value) {
                            return Promise.reject(new Error('两次输入的密码一致'));
                          }
                          return Promise.resolve();
                        },
                      }),
                    ]}
                  >
                    <Input.Password placeholder="请输入新密码" />
                  </Form.Item>
                </Form>
              </div>
            ) : (
              <div>
                <Form form={phoneForm}>
                  <Form.Item
                    name="phone"
                    label="手机号"
                    rules={[{ required: true, message: '请输入需要换绑的新手机号' }]}
                  >
                    <Input placeholder="请输入新的手机号绑定" />
                  </Form.Item>
                </Form>
              </div>
            )
          }
        </Modal>
      </div>

      {/* 自定义动画 CSS */}
      <style>{`
        @keyframes fadeIn {
          from { opacity: 0; }
          to { opacity: 1; }
        }
        
        @keyframes fadeInUp {
          from { 
            opacity: 0; 
            transform: translateY(20px); 
          }
          to { 
            opacity: 1; 
            transform: translateY(0); 
          }
        }
        
        @keyframes pulse {
          0% { transform: scale(1); }
          50% { transform: scale(1.1); }
          100% { transform: scale(1); }
        }
        
        @keyframes float {
          0% { transform: translateY(0px); }
          50% { transform: translateY(-5px); }
          100% { transform: translateY(0px); }
        }
        
        @keyframes progressGrow {
          from { width: 0%; }
          to { width: 100%; }
        }
        
        .fade-in {
          animation: fadeIn 0.8s ease forwards;
        }
        
        .fade-in-up {
          animation: fadeInUp 0.8s ease forwards;
        }
        
        .card-animate {
          opacity: 0;
          animation: fadeInUp 0.5s ease forwards;
        }
        
        .pulse-animation {
          animation: pulse 2s infinite;
        }
        
        .avatar-animate {
          animation: float 4s ease-in-out infinite;
        }
        
        .progress-animate {
          position: relative;
          animation: progressGrow 1s ease-out forwards;
        }
      `}</style>
    </div>
  );
};

export default memo(IndividualCenter);
